<?php
require_once(FWK_EXCEPTION."CustonException.class.php");
require_once(BIB_ACTIVE_RECORD);
require_once(FWK_MODEL."AbsModelDao.class.php");
require_once(FWK_MODEL."Upload.class.php");
require_once(FWK_UTIL."FormataDatas.class.php");
/**
 * Classe modelo para a transacao
 *
 * @author Vinicius Rodrigues <viniciusmr3@gmail.com>
 * @since 1.0 - 04/12/2012
 */
class Transacao extends AbsModelDao{

	public $_table = "transacoes";

	public $_id = "id_transacao";
	
	/**
	 * 
	 * Recupera o valor total de transacoes de resgate e expiracao de pontos do usuario
	 * @param  $id_usuario
	 */
	public function getValorTotalTransacoesPorUsuario($id_usuario) {
		$strQuery = "	
					 	SELECT SUM(valor_transacao)
		 
					FROM ".$this->_table."  t WHERE t.tipo_transacao != 3 AND t.id_usuario = ".$id_usuario;
		$arrRet = ControlDB::getRow($strQuery,3);
		return $arrRet;
	}
	
	public function getTransacaoPorVenda($id_venda) {
		$strQuery = "	
					 	SELECT id_transacao
		 
					FROM ".$this->_table."  t WHERE t.id_venda = ".$id_venda;
		$arrRet = ControlDB::getRow($strQuery,3);
		return $arrRet;
	}
	
	public function getSaldoPontosUsuario($id_usuario){
		$strQuery = "
		SELECT
		
		sum(t.pontos) as saldo_usuario
		
		FROM 
		
			(SELECT h.qtd_pontos AS 'pontos' 
				FROM historico_vendas h where h.data_venc_pontos > CURDATE()
				and h.id_usuario = ".$id_usuario.  
		
		"	UNION ALL 
		
			 SELECT p.pontos_premio AS 'pontos'
				FROM transacoes t INNER JOIN vouchers v ON (v.id_voucher = t.id_voucher)
							  	  INNER JOIN premios p ON (p.id_premio = v.id_premio)
			    WHERE t.tipo_transacao != 3 AND t.id_usuario = ".$id_usuario.  
			    
		"	) t
		
		";
	
		$arrRet = ControlDB::getRow($strQuery,3);
	return $arrRet;
	}
	
	public function getIdTransacByVoucher($idVoucher){
		$strQuery = "	
					 	SELECT id_transacao
		 
					FROM ".$this->_table."  t WHERE t.id_voucher = ".$idVoucher;
		$arrRet = ControlDB::getRow($strQuery,3);
		return $arrRet["id_transacao"];
	}
	

	public function alterar($id=null,$post,$file){
		try{
			self::salvaPostAutoUtf8($post);
			
			$this->id_transacao = $id;
					
			//campos default para todos os daos (data registro)
			$this->data_transacao = date("Y-m-d H:i:s");
			self::replace();
			if(self::ErrorMsg()){
				print("<pre>");
				print_r($post);
				die("<br/><br /><h1>".self::ErrorMsg()."</h1>");
			}
		}catch(DaoException $e){
			throw new CustonException($e->getMensagem());
		}
	}

}
?>